<?php

namespace addons\shopro\controller\order;

use app\admin\model\letter\LetterMaterial;
use app\common\model\letter\Letter;
use app\common\model\letter\LetterMailMethod;
use think\Db;
use addons\shopro\controller\Common;
use addons\shopro\service\order\OrderCreate;
use addons\shopro\service\order\OrderOper;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\Pay as PayModel;
use addons\shopro\library\express\Express as ExpressLib;
use think\Log;

class Order extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $user = auth_user();
        $params = $this->request->param();
        $type = $params['type'] ?? 'all';
        $o_type = $params['o_type'] ?? 0;
        $l_type = $params['l_type'] ?? -1;
        $order_type = $params['order_type'] ?? 'goods';
        $orders = OrderModel::where('user_id', $user->id)->with(['items', 'invoice']);

        // 新增订单类型筛选
        $orders = $orders->where(function ($query) use ($o_type, $l_type, $order_type) {
            if ($o_type) {// 信件订单
                $letter_type = $l_type;
                // 查询全部信件类型订单
                if ($l_type == -1) {
                    $letter_type = '1,2';
                }
                $query->whereIn('type', ['xj_goods', 'mxp_goods'])->whereIn('letter_type', $letter_type);
            } else {// 普通订单
                if ($order_type == 'goods') {
                    $query->whereIn('type', ['goods', 'xf_goods']);
                } else {
                    $query->where('type', $order_type);
                }
                $query->where(['letter_type' => '0']);
            }
        });

        switch ($type) {
            case 'unpaid':
                $orders = $orders->unpaid();
                break;
            case 'nosend':
                $orders = $orders->pretendPaid()->nosend();
                break;
            case 'noget':
                if ($order_type == 'yqs_goods') {
                    $orders = $orders->whereIn('status', ['nosend', 'noget', 'nocomment', 'paid']);
                } else {
                    $orders = $orders->pretendPaid()->noget();
                }
                break;
            case 'nocomment':
                $orders = $orders->paid()->nocomment();
                break;
            case 'completed':
                $orders = $orders->paid()->completed();
                break;
        }

        $orders = $orders->order('id', 'desc')->paginate(request()->param('list_rows', 10))->toArray();

        $orderModel = new OrderModel();
        foreach ($orders['data'] as &$order) {
            $orderSnArr = OrderModel::where(['original_order_id' => $order['id'], 'status' => 'unpaid', 'user_id' => $user->id])->column('order_sn');
            $order['is_need_pay'] = $orderSnArr ? 1 : 0;

            $order = $orderModel->setOrderItemStatusByOrder($order);

            if ($order['letter_type'] > 0) {
                // 查询信件信息
                $letter_info = Letter::where(['order_id' => $order['id'], 'uid' => $order['user_id']])->with(['template', 'explain', 'content'])->find();
                if ($letter_info) {


                    $letter_info['template'] = $letter_info['template'] ? $letter_info['template']->toArray() : '';
                    if ($letter_info['template']) {
                        $letter_info['template'] = ['image1' => $letter_info['template']['image'] ? explode(',', $letter_info['template']['image']) : ''];

                    }
                    $letter_info['photo'] = $letter_info['photo'] ? explode(',', $letter_info['photo']) : '';
                    $letter_info['postcard'] = $letter_info['postcard'] ? explode(',', $letter_info['postcard']) : '';
                    $letter_info['postcard_end'] = $letter_info['postcard_end'] ? explode(',', $letter_info['postcard_end']) : '';
                    $letter_info['material_list'] = [];
                    if ($letter_info['material_ids']) {
                        $letter_info['material_list'] = LetterMaterial::whereIn('id', $letter_info['material_ids'])->select();
                    }
                    if (!$letter_info['content']) {
                        $letter_info['content'] = [
                            'id' => 0,
                            'letter_id' => 0,
                            'uid' => 0,
                            'nickname' => '',
                            'content' => '无需内容',
                            'signature' => '',
                            'date' => '',
                            'diary_ids' => '',
                            'createtime' => '',
                            'updatetime' => '',
                        ];
                    }
                }
                $order['letter_info'] = $letter_info ?: [];


                $order['material_infos'] = $order['material_infos'] ? json_decode($order['material_infos'], true) : [];
                if ($order['material_infos']) {
                    foreach ($order['material_infos'] as $kk => $vv) {
                        $order['material_infos'][$kk]['m_image'] = $vv['m_image'];
                    }
                }
                $order['template_infos'] = $order['template_infos'] ? json_decode($order['template_infos'], true) : '';
                if ($order['template_infos']) {
                    $order['template_infos']['image'] = $order['template_infos']['image'] ? explode(',', $order['template_infos']['image']) : '';
                }

            } else {
                $order['status_text'] = $this->commonStatusText($order['status'], $order['type'], $order['status_text'], $order['items']);

            }
        }

        $this->success('获取成功', $orders);
    }


    public function commonStatusText($status, $type, $status_text, $items = [])
    {

        if ($type == 'yqs_goods') {
            switch ($status) {
                case 'nosend':
                    $status_text = '咨询中';
                    break;
                case 'noget':
                    $status_text = '咨询中';
                    break;
                case 'nocomment':
                    $status_text = '咨询中';
                    break;
                case 'paid':
                    $status_text = '咨询中';
                    break;
                case 'complete':
                    $status_text = '已完成';
                    break;
            }

            return $status_text;
        } else if ($type == 'pt_goods') {
            switch ($status) {
                case 'paid':
                    $status_text = '待配送';
                    if ($items && $items[0]['dispatch_status'] == 1) {
                        $status_text = '配送中';
                    }
                    if ($items && $items[0]['dispatch_status'] == 2) {
                        $status_text = '已送达';
                    }
                    break;
                case 'nosend':
                    $status_text = '待配送';
                    break;
                case 'noget':
                    $status_text = '配送中';
                    break;
                case 'nocomment':
                    $status_text = '已送达';
                    break;
                case 'complete':
                    $status_text = '已完成';
                    break;
            }
            return $status_text;
        } else {
            return $status_text;
        }
    }

    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $merchant_trade_no = $this->request->param('merchant_trade_no');
        $transaction_id = $this->request->param('transaction_id');
        Log::error('detail1：' . json_encode([
                'id' => $id,
                'merchant_trade_no' => $merchant_trade_no,
                'transaction_id' => $transaction_id,
                'user' => $user,
            ]));

        $order = OrderModel::where('user_id', $user->id)->with(['items', 'address', 'invoice']);

        if ($id) {
            $order = $order->where(function ($query) use ($id) {
                return $query->where('id', $id)->whereOr('order_sn', $id);
            });
        } else if ($merchant_trade_no) {
            $pay = PayModel::where('pay_sn', $merchant_trade_no)->findOrFail();
            $order = $order->where('id', $pay->order_id);
        } else {
            Log::error('detail2');
            $this->error('参数错误');
        }
        Log::error('detail3');

        $order = $order->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order->pay_types_text = $order->pay_types_text;
        // 处理未支付订单 item status_code
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了

        // 更新包裹信息（5分钟缓存）
        (new ExpressLib)->updateOrderExpress($order['id']);

        if ($order['letter_type']) {
            // 查询信件信息
            $letter_info = Letter::where(['order_id' => $order['id'], 'uid' => $order['user_id']])->with(['template', 'explain', 'content'])->find();
            if ($letter_info) {


                $letter_info['photo'] = $letter_info['photo'] ? explode(',', $letter_info['photo']) : '';
                $letter_info['handwriting_photo'] = $letter_info['handwriting_photo'] ? explode(',', $letter_info['handwriting_photo']) : '';
                if (isset($letter_info['template']) && $letter_info['template']) {
                    $letter_info['template']['image1'] = explode(',', $letter_info['template']['image']);
                }
                $letter_info['postcard'] = $letter_info['postcard'] ? explode(',', $letter_info['postcard']) : '';
                $letter_info['postcard_end'] = $letter_info['postcard_end'] ? explode(',', $letter_info['postcard_end']) : '';
                $letter_info['material_list'] = [];
                if ($letter_info['material_ids']) {
                    $letter_info['material_list'] = LetterMaterial::whereIn('id', $letter_info['material_ids'])->select();
                }
                if (!$letter_info['content']) {
                    $letter_info['content'] = [
                        'id' => 0,
                        'letter_id' => 0,
                        'uid' => 0,
                        'nickname' => '',
                        'content' => '无需内容',
                        'signature' => '',
                        'date' => '',
                        'diary_ids' => '',
                        'createtime' => '',
                        'updatetime' => '',
                    ];
                }
            }
            $order['letter_info'] = $letter_info ?: [];

            $order['material_infos'] = $order['material_infos'] ? json_decode($order['material_infos'], true) : '';
            if ($order['material_infos']) {
                foreach ($order['material_infos'] as $kk => $vv) {
                    $order['material_infos'][$kk]['m_image'] = $vv['m_image'];
                }
            }
            $order['template_infos'] = $order['template_infos'] ? json_decode($order['template_infos'], true) : '';
            if ($order['template_infos']) {
                $order['template_infos']['image'] = $order['template_infos']['image'] ? explode(',', $order['template_infos']['image']) : '';
            }
        }
        if ($order['type'] == 'pt_goods') {
            $order['daisong'] = Db::table('jy_letter_user_daisong_log')->where(['order_id' => $order['id']])->find();
            $order['status_desc'] = $this->commonStatusText($order['status'], $order['type'], $order['status_text'], $order['items']);
        }
        if ($order['type'] == 'yqs_goods') {
            $order['chat_end_time'] = date('Y-m-d H:i:s', $order['chat_end_time']);
            $order['status_desc'] = $this->commonStatusText($order['status'], $order['type'], $order['status_text']);
        }

        $this->success('获取成功', $order);
    }


    public function itemDetail()
    {
        $user = auth_user();

        $id = $this->request->param('id');
        $item_id = $this->request->param('item_id');
        Log::error('itemDetail1:' . json_encode([
                'id' => $id,
                'item_id' => $item_id,
            ]));

        if (!$id || !$item_id) {
            Log::error('itemDetail2');
            $this->error('参数错误');
        }
        Log::error('itemDetail3');

        $order = OrderModel::with(['items' => function ($query) use ($item_id) {
            $query->where('id', $item_id);
        }])->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order || !$order->items) {
            $this->error(__('No Results were found'));
        }

        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        $item = $order['items'][0];

        $this->success('获取成功', $item);
    }


    public function calc()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".calc");

        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->calc();

        if (isset($result['msg']) && $result['msg']) {
            $this->error($result['msg'], 1, $result);
        } else {
            $this->success('计算成功', $result);
        }
    }


    public function create()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".create");

        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->calc('create');

        $order = $orderCreate->create($result);

        $this->success('订单添加成功', $order);
    }


    /**
     * 获取用户可用和不可用优惠券
     *
     * @param Request $request
     * @return void
     */
    public function coupons()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".create");

        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->getCoupons();

        $this->success('获取成功', $result);
    }


    // 取消订单
    public function cancel()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = Db::transaction(function () use ($id, $user) {
            $order = OrderModel::canCancel()->where('user_id', $user->id)->with(['items', 'invoice'])->lock(true)->where('id', $id)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }

            $orderOper = new OrderOper();
            $order = $orderOper->cancel($order, $user, 'user');

            return $order;
        });
        // 订单未支付，处理 item 状态
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了

        $this->success('取消成功', $order);
    }


    // 订单申请全额退款
    public function applyRefund()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->applyRefund($order, $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        $this->success('申请成功', $order);
    }

    // 确认收货(货到付款的确认收货在后台)
    public function confirm()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->confirm($order, [], $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $this->success('收货成功', $order);
    }


    // 评价
    public function comment()
    {
        $user = auth_user();
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        $this->svalidate($params, ".comment");

        $comments = $params['comments'] ?? [];
        foreach ($comments as $comment) {
            $this->svalidate($comment, ".comment_item");
        }

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $params, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->comment($order, $params['comments'], $user, 'user');

            return $order;
        });

        $this->success('评价成功', $order);
    }


    /**
     * 用户是否存在未支付的，当前团的订单
     *
     * @param Request $request
     * @return void
     */
    public function unpaidGrouponOrder()
    {
        $user = auth_user();

        $params = $this->request->param();
        $activity_id = $params['activity_id'] ?? 0;

        if ($user && $activity_id) {
            $order = OrderModel::unpaid()->where('user_id', $user->id)
                ->where('activity_id', $activity_id)
                ->whereIn('activity_type', ['groupon', 'groupon_ladder'])->find();
        }

        $this->success('获取成功', $order ?? null);
    }


    // 删除订单
    public function delete()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::canDelete()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单不存在或不可删除');
        }

        Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $orderOper->delete($order, $user, 'user');
        });

        $this->success('删除成功');
    }

    // 修改订单前的检测
    public function check_edit_order()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $order = OrderModel::canEdit()->where('user_id', $user->id)->with(['items', 'invoice'])->lock(true)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        if (!$order['letter_type']) {
            $this->error(__('非信件订单，不允许操作'));
        }

        // 查询是否存在未支付的差价订单
        $orderSnArr = OrderModel::where(['original_order_id' => $order['id'], 'status' => 'unpaid', 'user_id' => $user->id])->column('order_sn');
        if ($orderSnArr) {
            $this->error(__('存在未支付的差价订单，请先支付后再提交修改'), ['order_sn' => $orderSnArr]);
        }

        $this->success('can_edit');
    }


    // 修改订单
    public function edit_order()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $newNickname = $this->request->param('nickname') ?? '';
        $newSignature = $this->request->param('signature') ?? '';
        $newDate = $this->request->param('date') ?? date('Y年m月d日', time());
        $newContent = $this->request->param('content', ''); // 新的信件内容
        $newPhotos = $this->request->param('photos', []); // 新的照片数组
        $newHandwritingPhotos = $this->request->param('handwriting_photo', []); // 新的照片数组
        $newTemplateId = $this->request->param('template_id');// 新的模板ID
        $removePhotoIds = $this->request->param('remove_photo_ids', []); // 要删除的照片ID

        $order = Db::transaction(function () use ($id, $user, $newNickname, $newSignature, $newDate, $newContent, $newPhotos, $newHandwritingPhotos, $newTemplateId) {
            $order = OrderModel::canEdit()->where('user_id', $user->id)->with(['items', 'invoice'])->lock(true)->where('id', $id)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }

            if (!$order['letter_type']) {
                $this->error(__('非信件订单，不允许操作'));
            }

            if ($order['original_order_id']) {
                $this->error(__('补差价订单，不允许操作'));
            }

            // 查询是否存在未支付的差价订单
            $existsNotPay = OrderModel::where(['original_order_id' => $order['id'], 'status' => 'unpaid', 'user_id' => $user->id])->find();
            if ($existsNotPay) {
                $this->error(__('存在未支付的差价订单，请先支付后再提交修改'));
            }

            if (!$newTemplateId) {
                $this->error(__('请选择模板'));
            }

            $orderOper = new OrderOper();
            $order = $orderOper->editOrder($order,
                $user,
                'user',
                [
                    'new_nickname' => $newNickname,
                    'new_signature' => $newSignature,
                    'new_date' => $newDate,
                    'new_content' => $newContent,
                    'new_photos' => $newPhotos,
                    'new_handwriting_photo' => $newHandwritingPhotos,
                    'new_template_id' => $newTemplateId,
                ]);

            return $order;
        });

        $this->success('修改成功', $order);
    }

    /**
     * 获取信件邮寄方式
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLetterMailMethod()
    {
        $list = LetterMailMethod::where(['status' => 1])->field('id,name,price,is_logistics')->select();
        $this->success('获取成功', $list);
    }
}
